package com.itheima.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ser.impl.UnknownSerializer;
import com.itheima.commen.Result;
import com.itheima.entiry.User;
import com.itheima.service.UserService;
import com.itheima.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public Result sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (!StringUtils.isEmpty(phone)){
            String msg = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",msg);
            session.setAttribute(phone,msg);
            redisTemplate.opsForValue().set("msg",msg);
            return new Result(1);
        }
        return new Result(0);
    }

    @PostMapping("/login")
    public Result login1(@RequestBody Map map, HttpSession session){

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
//        String codeSession = (String) session.getAttribute(phone);
        String redisMsg = (String) redisTemplate.opsForValue().get("msg");
        if (redisMsg!=null&&redisMsg.equals(code)){
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone,phone);
            User user = userService.getOne(qw);
            if (user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            redisTemplate.delete("msg");
            session.setAttribute("user",user.getId());
//            redisTemplate.opsForValue().set("user",user.getId());
            return new Result(1);
        }
        return new Result(0);

    }

    @PostMapping("/loginout")
    public Result loginOut(HttpSession session){
        session.removeAttribute("user");
        return new Result(1);
    }
}
